/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.persistence.memory;

import apus.entity.Call;
import apus.entity.PhoneNumber;
import apus.persistence.CallDAO;
import apus.persistence.PhoneNumberDAO;
import apus.services.ServiceLocator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author  Maxim Vasilevsky
 * @author  Roman Dyatkovsky
 * @since APUS v0.2
 * @see AbstractMemoryDAO
 * @see CallDAO
 */
public class MemoryCallDAO extends AbstractMemoryDAO<Call> implements CallDAO{
    
    private static Map<Integer,Call> dataSource = new HashMap<>();
    private static int counter;

    @Override
    public void create(Call entity) {
        super.create(entity);
        
        PhoneNumberDAO phoneNumberDAO = ServiceLocator.getService(PhoneNumberDAO.class);
        
        PhoneNumber from = phoneNumberDAO.readByNumber(entity.getNumberFrom().getNumber());
        PhoneNumber to = phoneNumberDAO.readByNumber(entity.getNumberTo().getNumber());
        
        from.addOutCall(entity);
        to.addInCall(entity);
        
        phoneNumberDAO.update(from);
        phoneNumberDAO.update(to);
    }
    
    @Override
    protected Map<Integer, Call> getDataSource() {
        return dataSource;
    }

    @Override
    protected Integer getAndIncreaseCounter() {
        return counter++;
    }

    
    @Override
    public Call readByNumbersAndTime(PhoneNumber out, PhoneNumber in, Date dateOfCall) {
        for (Call call:dataSource.values()){
            if ((call.getNumberFrom().equals(out))&&(call.getNumberTo().equals(in))&&(call.getDateOfCall().equals(dateOfCall))){
                return call;
            }
        }
        return null;
    }
    
}
